package com.fox.imagedb.gui;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.imgscalr.Scalr.Mode;

import com.fox.imagedb.listener.ImageDBMouseListener;

public class ImagePanel extends JLabel {

	private static final long serialVersionUID = 1L;

	public ImagePanel() {
		super();
		addMouseListener(new ImageDBMouseListener(this));
	}

	public void updateImage(File imageFile) {
		BufferedImage img = null;
		try {
			img = ImageIO.read(imageFile);
			BufferedImage resizedBufferedImage = Scalr.resize(img,
					Method.AUTOMATIC, Mode.FIT_EXACT, getWidth(), getHeight());
			this.setIcon(new ImageIcon(resizedBufferedImage));
		} catch (IOException e) {
		}

		/*
		 * Image newimg = icon.getImage().getScaledInstance(getWidth(),
		 * getHeight(), java.awt.Image.SCALE_FAST);
		 */

	}

	public void resizeImage(int width, int height) {
		if (width < 0) {
			width = getWidth();
		}
		if (height < 0) {
			height = getHeight();
		}
		if (getIcon() != null) {
			BufferedImage img = createBufferedImage((ImageIcon) getIcon());
			BufferedImage resizedBufferedImage = Scalr.resize(img,
					Method.AUTOMATIC, Mode.FIT_EXACT, width, height);

			/*
			 * Image newimg = ((ImageIcon) getIcon()).getImage()
			 * .getScaledInstance(getWidth(), getHeight(),
			 * java.awt.Image.SCALE_FAST);
			 */
			this.setIcon(new ImageIcon(resizedBufferedImage));
		}
	}

	private BufferedImage createBufferedImage(ImageIcon icon) {
		Image source = icon.getImage();
		int w = source.getWidth(null);
		int h = source.getHeight(null);
		BufferedImage image = new BufferedImage(w, h,
				BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = (Graphics2D) image.getGraphics();
		g2d.drawImage(source, 0, 0, null);
		g2d.dispose();
		return image;
	}
}
